/*
 * @Author: silence
 * @Date: 2022-05-27 10:46:56
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-07-27 17:40:30
 * @Description: 
 */
import 'package:flutter/material.dart';
import '../../../bloc/userbloc/user_bloc.dart';
import '../../../entities/UserEntity.dart';
import '../../../utils/eventBus/eventBus.dart';
import '../../../utils/string/StringConstant.dart';
import 'package:shared_preferences/shared_preferences.dart';

/**
 * 轻量级缓存工具
 */

class SpUtils {
  static SharedPreferences? _sharedPreferences;
  static String userInfo = 'SpUtils.userInfo';
  static String checkInfo = 'SpUtils.checkInfo';

  static test() {}

  //初始化，在程序最开始的地方调用
  static Future init({required BuildContext context}) async {
    _sharedPreferences = await SharedPreferences.getInstance();

    test();
    // 初始化完成
    bus.emit(StringConstant.SpUtilsInitFinished, true);

    //获取用户凭证
    UserBlocTool.getUserAuth();

    //获取登录用户，刷新各大首页布局
    UserEntity? user = UserBlocTool.getUser();
    if (user != null) {
      UserBlocTool.update(context, user);
      bus.emit(StringConstant.UserLoginInEvent);
      print('自动登录-------发送登录成功的通知---------');
    }

    //初始化完成后发出通知
    bus.emit(StringConstant.SpInitedEvent, true);
  }

  static String? getData(String key) {
    if (_sharedPreferences == null) {
      return "";
    }
    return _sharedPreferences!.getString(key);
  }

  static Future saveData(String key, String data) async {
    return await _sharedPreferences!.setString(key, data);
  }

  static bool getBoolData(
    String key,
  ) {
    return _sharedPreferences!.getBool(key) ?? false;
  }

  static Future remove(String key) async {
    return await _sharedPreferences!.remove(key);
  }

  static Future saveBoolData(String key, bool data) async {
    return await _sharedPreferences!.setBool(key, data);
  }

  static int? getIntData(
    String key,
  ) {
    return _sharedPreferences!.getInt(key);
  }

  static Future saveIntData(String key, int data) async {
    return await _sharedPreferences!.setInt(key, data);
  }
}
